//
// Created by lzc on 2023/1/14.
//

#include "arg.h"
#include "sys/socket.h"
#include "arpa/inet.h"
#include "pthread.h"
#include "sock.h"
#include <unistd.h>
#include "dirent.h"
#include "sys/stat.h"

int init_cli(ClientArgs args){
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0){
        printf("create socket fail\n");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in serv_addr = {};
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(args.port);
    inet_aton(args.server, &serv_addr.sin_addr);

    int rv = connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    if (rv < 0) {
        printf("fail to connect to %s:%d\n", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
        exit(EXIT_FAILURE);
    }

    return sockfd;
}

int main(int argc, char *argv[]){
    ClientArgs args;
    parse_cli_args(&args, argc, argv);

    printf("list: %d, server: %s, port: %d, dl: %s, output: %s\n",
           args.list, args.server, args.port, args.dl, args.output);

    int sockfd = init_cli(args);
    struct stat temp_buff;
    if (args.list){
        sendStr(sockfd, "list");
        printf(recStr(sockfd));
    } else {
        if (lstat(args.output, &temp_buff) == 0) {
            printf("failed to download %s, %s already exists", args.output, args.output);
            exit(EXIT_FAILURE);
        }
        sendStr(sockfd, "dl");
        sendStr(sockfd, args.dl);
        recFile(sockfd, strlen(args.output)==0 ? args.dl : args.output);
    }

    close(sockfd);
    return 0;
}